/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 单号充值记录
 *  */
import React, { useRef } from 'react';
import { useAntdTable, useDebounceFn } from 'ahooks';
import { useDispatch } from 'dva';
import { Form, DatePicker, Row, Col, Button, Select, Avatar, Input } from 'antd';
import StandardTable from '@/components/StandardTable';
import moment from 'moment';
import styles from './style.less';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;

const format = 'YYYY-MM-DD';

const today = moment()
  .startOf('day')
  .subtract(0, 'days');
const startDay = moment()
  .startOf('day')
  .subtract(7, 'days');

const disabledDate = current =>
  current &&
  current >
    moment()
      .endOf('day')
      .subtract(0, 'days');

const formatScanTimeField = (scanTime = []) => {
  const [start, end] = scanTime;
  const startTime = moment(start).format(format);
  const endTime = moment(end).format(format);
  return {
    startTime,
    endTime,
  };
};

/** all字段的替换 */
const formatField = (field = {}) => {
  const { user_role } = field;
  return {
    ...field,
    user_role: user_role === 'all' ? '' : user_role,
  };
};

const ChargeRecords = ({ form }) => {
  const { validateFields, getFieldDecorator, resetFields } = form;
  const dispatch = useDispatch();
  const tableList = useRef([]);

  const columns = [
    {
      width: 200,
      title: '时间',
      key: 'create_time',
      dataIndex: 'create_time',
    },
    {
      width: 100,
      title: '客户类型',
      key: 'courieTypeName',
      dataIndex: 'courieTypeName',
    },
    {
      width: 150,
      title: '名称',
      key: 'courieName',
      dataIndex: 'courieName',
    },
    {
      width: 150,
      title: '联系电话',
      key: 'couriePhone',
      dataIndex: 'couriePhone',
    },
    {
      width: 300,
      title: '单号源类型、账号',
      key: 'content',
      dataIndex: 'content',
    },
    {
      width: 300,
      title: '单号源',
      key: 'info',
      dataIndex: 'info',
      render: (info, { brand }) => (
        <Row type="flex" gutter={[20, 20]} align="middle">
          <Col>
            <Avatar size="large" src={`//img.kuaidihelp.com/brand_logo/icon_${brand}.png`} />
          </Col>
          <Col>{info}</Col>
        </Row>
      ),
    },
    {
      width: 100,
      align: 'center',
      title: '设置数量',
      key: 'quantity',
      dataIndex: 'quantity',
      render: (quantity, { set_type }) => {
        if (set_type == 'unLimit') {
          return <span style={{ color: 'orange' }}>单号不限</span>;
        }
        return <span style={{ color: quantity > 0 ? 'green' : 'red' }}>{quantity}票</span>;
      },
    },
  ];

  const getTableList = async ({ current }, formData) => {
    const { scanTime = [], scanner, waybill_no, ...rest } = formData;

    const { list = [], pagination = {} } = await dispatch({
      type: 'setter/getOrderChargeRecords',
      payload: {
        pageNum: current,
        pageSize: 15,
        ...formatScanTimeField(scanTime),
        ...formatField(rest),
      },
    });
    tableList.current = list;
    return {
      list,
      total: pagination.total,
    };
  };

  const { tableProps, search, loading } = useAntdTable(getTableList, {
    defaultPageSize: 15,
    defaultParams: [
      { current: 1, pageSize: 15 },
      { scanTime: [startDay, today], user_role: 'all' },
    ],
    form,
  });

  const { run: onSubmit } = useDebounceFn(
    () => {
      validateFields(err => {
        if (err) return;
        search.submit();
      });
    },
    {
      wait: 300,
      leading: true,
      trailing: false,
    },
  );

  const { run: reset } = useDebounceFn(
    () => {
      tableList.current = [];
      resetFields();
      search.submit();
    },
    {
      wait: 300,
      leading: true,
      trailing: false,
    },
  );

  return (
    <div className={styles.main}>
      <Form layout="inline">
        <FormItem>
          {getFieldDecorator('scanTime', {
            initialValue: [startDay, today],
          })(<RangePicker allowClear={false} style={{ width: 300 }} disabledDate={disabledDate} />)}
        </FormItem>
        <FormItem>
          {getFieldDecorator('user_role', {
            initialValue: 'all',
          })(
            <Select style={{ width: 150 }}>
              <Select.Option value="all" key="all">
                全部客户类型
              </Select.Option>
              <Select.Option value="8" key="8">
                业务员
              </Select.Option>
              <Select.Option value="5" key="5">
                微商
              </Select.Option>
              <Select.Option value="2" key="2">
                驿站
              </Select.Option>
            </Select>,
          )}
        </FormItem>
        <FormItem>
          {getFieldDecorator('keyWord')(
            <Input placeholder="可根据联系电话、名称搜索" allowClear style={{ width: 220 }} />,
          )}
        </FormItem>
        <FormItem>
          <Row type="flex" gutter={[20, 20]}>
            <Col>
              <Button type="primary" icon="search" onClick={onSubmit} loading={loading}>
                查询
              </Button>
            </Col>
            <Col>
              <Button onClick={reset}>重置</Button>
            </Col>
          </Row>
        </FormItem>
      </Form>
      <StandardTable
        scroll={{ x: 900 }}
        loading={loading}
        rowKey="id"
        data={{
          list: tableProps.dataSource,
          pagination: {
            ...tableProps.pagination,
            showQuickJumper: false,
            showSizeChanger: false,
          },
        }}
        columns={columns}
        onChange={tableProps.onChange}
      />
    </div>
  );
};

export default Form.create()(ChargeRecords);
